{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# The NumPy Library\n", "\n", "## Try me\n", " [![Open In Colab](../../_static/colabs_badge.png)](https://colab.research.google.com/github/ffraile/operations-research-notebooks/blob/main/docs/source/Introduction/libraries/Numpy%20tutorial.ipynb)[![Binder](../../_static/binder_badge.png)](https://mybinder.org/v2/gh/ffraile/operations-research-notebooks/main?labpath=docs%2Fsource%2FIntroduction%2Flibraries%2FNumpy%20tutorial.ipynb)\n", "\n", "The [Numpy](https://numpy.org/) (Numerical Python) is a package of numerical functions to effectively work with multidimensional data structures in Python. In Python, it is possible to work with nested lists to work with multidimensional structures (arrays and matrix), but this is not efficient. The Numpy library defines the numpy array object to provide an efficient and convenient object to define multidimensional structures.\n", "\n", "To use Numpy in your Notebooks and programs, you first need to import the package (in this example we use the alias np):" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The Numpy Array\n", "\n", "The numpy array uses a similar structure to a Python list, although as mentioned above, it provides additional functionalities to easily create and manipulate multidimensional data structures. The data in an array are called elements, and they are accessed using brackets, just as with Python lists. The dimensions of a numpy array are called **axes**. The elements within an axe are separated using commas and surrounded by brackets. Axes are also separated by brackets, so that a numpy array is represented as an nested python list. The **rank** is the number of axis of an array. The **shape** is a list representing the number of elements in each axis. The elements of a numpy array can be of any numerical type." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "My first Numpy array:\n", "[[1 2 3 4]\n", " [5 6 7 8]]\n", "element in position (1,2) is:\n", "7\n", "Number of dimensions:\n", "2\n", "Shape of array:\n", "(2, 4)\n", "Total number of elements:\n", "8\n" ] } ], "source": [ "b = np.array([[1,2,3,4],[5,6,7,8]]) #This creates a 2-dimensional (rank 2) 2x4 array \n", "print(\"My first Numpy array:\")\n", "print(b) \n", " \n", "print(\"element in position (1,2) is:\")\n", "print(b[1,2])\n", "\n", "print(\"Number of dimensions:\")\n", "print(b.ndim) #number of dimensions or rank\n", "\n", "print(\"Shape of array:\")\n", "print(b.shape) #shape (eg n rows, m columns)\n", "\n", "print(\"Total number of elements:\")\n", "print(b.size) #number of elements" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create Numpy Arrays\n", "\n", "Numpy includes several functions for creating numpy arrays initialized with convenient ranks, shapes, or elements with constant or random values.\n", "\n", "**Some examples:**\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1. 1.]\n", " [1. 1.]\n", " [1. 1.]]\n", "[[0. 0. 0. 0.]\n", " [0. 0. 0. 0.]\n", " [0. 0. 0. 0.]]\n", "[0.71574091 0.54968971 0.72723399]\n", "[[12 12]\n", " [12 12]]\n", "[[1. 0. 0.]\n", " [0. 1. 0.]\n", " [0. 0. 1.]]\n" ] } ], "source": [ "o = np.ones((3,2)) # array of 3x2 1s\n", "print(o)\n", "\n", "b=np.zeros((3,4)) # array of 3x4 zeroes\n", "print(b)\n", "\n", "c=np.random.random(3) #array of 3x1 random numbers\n", "print(c)\n", "\n", "d=np.full((2,2),12) # array of 2x2 12s\n", "print(d)\n", "\n", "id =np.eye(3,3) # identity array of size 3x3\n", "print(id)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Creating sequences\n", "\n", "Some useful functions for creating lists are **arange** and **linspace**:\n", "\n", " - **arange(start, end, step)**: creates a numpy array with elements ranging from **start** to **end** incrementing by **step**. Only end is required, using only end will create an evenly spaced range from 0 to end.\n", " - **linspace(start,end,numvalues)**: creates a numpy array with **numvalues** elements with evenly distributed values ranging from **start** to **end**. The increment is calculated by the function so that the resulting number of elements matches the numvalues input parameter.\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0 2 4 6 8]\n", "[ 0. 2. 4. 6. 8. 10.]\n" ] } ], "source": [ "a = np.arange(0, 10, 2)\n", "print(a)\n", " \n", "b=np.linspace(0,10,6)\n", "print(b)\n", " \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Arithmetic operations\n", "\n", "You can apply element-wise **arithmetic** and **logical** calculations to numpy arrays using arithmetic or logical operators. The functions np.**exp()**, np.**sqrt()**, or np.**log()** are other examples of functions that operate in the elements of a numpy array. You can check the entire list of available functions in the official [Numpy documentation]( https://numpy.org/doc/).\n", "**Some examples:**" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[10 12 14 16]\n", " [18 20 22 24]]\n", "[[8 8 8 8]\n", " [8 8 8 8]]\n", "[[3. 3.16227766 3.31662479 3.46410162]\n", " [3.60555128 3.74165739 3.87298335 4. ]]\n", "[[0. 0.69314718 1.09861229 1.38629436]\n", " [1.60943791 1.79175947 1.94591015 2.07944154]]\n", "[[ 1 4 9 16]\n", " [25 36 49 64]]\n", "[[ 6 7 8 9]\n", " [10 11 12 13]]\n" ] } ], "source": [ "x =np.array([[1,2,3,4],[5,6,7,8]])\n", "y =np.array([[9,10,11,12],[13,14,15,16]])\n", "print(x+y)\n", "print(y-x)\n", "print(np.sqrt(y))\n", "print(np.log(x))\n", "print(x**2)\n", "print(x+5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Note that in the last examples, we are adding a scalar value to a numpy array. In general, we can apply arithmetic operations on array of different dimensions, given that the smallest dimension between the operands is one, or that the arrays have the same dimensions. When this condition is met, numpy will expand the smaller array to match the shape of the larger array with an operation called **broadcasting**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Array functions\n", "Numpy also provides an extensive list of array functions:\n", "\n", " - **sum()**: Returns the sum of all elements.\n", " - **min()**: Returns the minimum value within the array\n", " - **max()**: Returns the maximum value within the array\n", " - **mean()**: Returns the mean of an array\n", " - **median()**: Returns the median value of the array\n", " - **cumsum()**: Returns the cumulative sum of the elements of the array.\n", " \n", " All the functions above support the additional **axis** parameter to work on a specific dimension." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sum of all elements in x:\n", "36\n", "mean value of y:\n", "12.5\n" ] } ], "source": [ "x =np.array([[1,2,3,4],[5,6,7,8]])\n", "y =np.array([[9,10,11,12],[13,14,15,16]])\n", "\n", "print(\"sum of all elements in x:\")\n", "print(np.sum(x))\n", "\n", "print(\"mean value of y:\")\n", "print(np.mean(y))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other functions take two arrays as arguments and perform element wise operations:\n", "\n", "- minimum(): Returns an array with the minimum value in each position of the array\n", "- maximum(): Returns an array with the maximum value in each position of the array" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0. 0.11111111 0.22222222 0.0069694 0.44444444 0.3403326\n", " 0.19167794 0.71257103 0.78045669 0.64287305]\n" ] } ], "source": [ "b=np.linspace(0,1,10)\n", "r = c=np.random.random(10)\n", "print(np.minimum(b,r))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.4" }, "pycharm": { "stem_cell": { "cell_type": "raw", "source": [], "metadata": { "collapsed": false } } } }, "nbformat": 4, "nbformat_minor": 2 }